package com.quiz.quazz.client;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class PlayerList {

	private List<Player> players;

	public PlayerList() {
		this.players = new ArrayList<Player>();
	}

	public List<Player> getPlayers() {
		return getRankedPlayerList();
	}

	public Integer getPlayerCount() {
		if (this.players != null) {
			return this.players.size();
		} else {
			return 0;
		}
	}

	public void addPointsToPlayer(String ip, Integer points) {
		getPlayerByIp(ip).addPoints(points);
	}

	public void removePointsFromPlayer(String ip, Integer points) {
		getPlayerByIp(ip).removePoints(points);
	}

	public Player getPlayerByIp(String ip) {
		for (Player player : this.players) {
			if (player.getIp().equals(ip)) {
				return player;
			}
		}
		return null;
	}

	public void setPlayers(List<Player> players) {
		this.players = players;
	}

	public void addPlayer(Player player) {
		if (players == null) {
			players = new ArrayList<Player>();
		}
		if (!this.players.contains(player)) {
			players.add(player);
		}
	}

	public void addAllPlayers(List<Player> players) {
		if (this.players == null) {
			players = new ArrayList<Player>();
		}
		players.addAll(players);
	}

	public void removePlayerByIp(String ip) {
		Player playerByIp = getPlayerByIp(ip);
		if (players != null && players.contains(playerByIp)) {
			players.remove(playerByIp);
		}
	}

	public void removeAllPlayers(List<Player> players) {
		if (this.players != null && players != null) {
			if (players.containsAll(players)) {
				players.removeAll(players);
			} else {
				for (Player player : players) {
					this.players.remove(player);
				}
			}
		}
	}

	public Player getWinner() {
		return getPlayers().get(0);
	}

	public List<Player> getRankedPlayerList() {
		Collections.sort(this.players, new WinnerComparator());
		return this.players;
	}

	class WinnerComparator implements Comparator<Player> {
		@Override
		public int compare(Player p1, Player p2) {
			return p1.compareTo(p2);
		}
	}
}
